/**
 *
 */
package com.angel.data.generator.checkers.impl;

import java.util.ArrayList;
import java.util.List;

import com.angel.data.generator.checkers.DataGeneratorChecker;
import com.angel.data.generator.exceptions.DataGeneratorException;
import com.angel.data.generator.interfaces.DataGenerator;
import com.angel.data.generator.repository.DataGeneratorRepository;

/**
 * @author William
 *
 */
public class DependsDataGeneratorDependenceNotAddedChecker implements DataGeneratorChecker{


	@SuppressWarnings("unchecked")
	public void checkDataGenerator(DataGenerator dataGenerator, DataGeneratorRepository dataGeneratorRepository) throws DataGeneratorException {
		DataGenerator[] dataGeneratorDependencies = dataGeneratorRepository.getDependenciesFor((Class<? extends DataGenerator>) dataGenerator.thisDataGeneratorClass());//DataGeneratorRepository.getInstance().getDependenciesFor(dataGenerator.getClass());
		if(dataGeneratorDependencies != null && dataGeneratorDependencies.length > 0 && dataGeneratorRepository.size() > 0){
			for(DataGenerator dataGeneratorDependency: dataGeneratorDependencies){
				int dependenceCount = dataGeneratorDependencies.length;
				for(DataGenerator dependency: dataGeneratorRepository.getDependencies()){
					if(dataGeneratorDependency.getClass().equals(dependency.getClass())){
						dependenceCount--;
					}
				}
				if( dependenceCount > 0){
					throw new DataGeneratorException("Some dependencies for data generator class [" + dataGenerator.getClass() + "] was not found. It found only [" + dependenceCount + "] dependences.");
				}
			}
		}
	}

	@SuppressWarnings("unused")
	private <T> DataGenerator[] getDependenciesFor(DataGenerator dataGenerator, DataGenerator[] dependencies){
		List<DataGenerator> a = new ArrayList<DataGenerator>();
		if(dependencies != null && dependencies.length > 0){
			for(DataGenerator dg: dependencies){
				Class<?>[] dependEachDG = dg.getDependecesGenerators();
				for(Class<?> dedgClass: dependEachDG){
					if(dedgClass.equals(dataGenerator.thisDataGeneratorClass())){
						a.add(dg);
					}
				}
			}
		}
		return a.toArray(new DataGenerator[a.size()]);
	}


}
